package com.example.redisdemo.netty.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 心跳检测
 *
 * @author hexinglin
 * @created 2022-05-26 14:56
 **/
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if( evt instanceof IdleStateEvent){
            //将Evt向下转型
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            String eventType = null;
            switch(idleStateEvent.state() ){
                case READER_IDLE:
                    eventType = "读空闲";
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
                case ALL_IDLE:
                    eventType = "读写空闲";
                    System.out.println(ctx.channel().remoteAddress()+"长时间闲置，断开链接");
                    ctx.close();
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + idleStateEvent.state());
            }

            System.out.println("服务器做响应的处理...");
        }
    }
}

